#include "usb_echo.h"

#define USB_ECHO_SIZE	(2048)
#define USB_PKG_NUM	(32)
#define USB_PKG_SIZE	(1024)

#define USB_PKG_HEAD	'*'
#define USB_PKG_TAIL	'#'

static u8 *usbRcvBuf=NULL;
static fifo_t usbRcvFifo;
static u8 usbPkgHead;
static LinkQueue usbPkgQue;

static void usb_pkg_proc(void)
{
	//usbe_debug("[USBE] usb_pkg_proc ...\n");
}


void usb_data_parse_pkg(void)
{
	u8 ch, *buf;
	USB_PKG_CELL *cell;
	
	while(!fifo_empty(&usbRcvFifo)){
		if (queue_get(&usbPkgQue) > USB_PKG_NUM) return;

		fifo_get8(&usbRcvFifo, (u8 *)&ch);
		usbe_debug("[USBE] RCV: %c\n", ch);

		if((USB_PKG_HEAD == ch) && (usbPkgHead==0)){
			//  if (QueueItem(&usbPkgQue) > USB_PKG_NUM) return;
			  cell = (USB_PKG_CELL *)pvPortMalloc(sizeof(USB_PKG_CELL));
			  if(cell != NULL){
				buf= (u8 *)pvPortMalloc(USB_PKG_SIZE);
				if(buf == NULL){
					vPortFree(cell);
					return ;
				}else{
					cell->body = buf;
					cell->len = 0;
				}
				usbPkgHead = 1;
				cell->body[cell->len++] = ch;
			  }
		}

		// parse pkg data 
		//  head ... cmd ... data ... crc ... tail
		// push to fifo

		

	}

	usb_pkg_proc();
}

void usb_rcv_buf_push(u8 data)
{
	fifo_put8(&usbRcvFifo, data);
}

u8 usb_echo_init(void)
{
	usbPkgHead = 0;
	
	usbRcvBuf = (u8 *)pvPortMalloc(USB_ECHO_SIZE);
	if(!usbRcvBuf){
		usbe_debug("[USBE] usb malloc usbRcvBuf err!\n");
		return 1;
	}

	fifo_init(&usbRcvFifo, usbRcvBuf, USB_ECHO_SIZE);
	queue_init(&usbPkgQue);    

	usbe_debug("[USBE] usb_echo_init !\n");
	
	return 0;
}


